﻿using System;

using Fuse8.DomainFramework.Domain;
using Fuse8.DomainFramework.Common;
using Fuse8.DomainFramework.Common.Locator;

namespace Fuse8.DomainFramework.ValidationService
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ValidationFacade<T> : IEntityValidationService<T> where T : class, IEntityObject
    {
        private IEntityValidationService<T> _service = null;

        /// <summary>
        /// 
        /// </summary>
        protected virtual IEntityValidationService<T> Service
        {
            get
            {
                if (_service == null)
                {
                    _service = DependencyServiceLocator.Current.GetInstance<IEntityValidationService<T>>();
                }

                return _service;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public ValidationFacade()
            : this(new BaseEntityValidationService<T>())
        { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="validationService"></param>
        public ValidationFacade(IEntityValidationService<T> validationService)
        {
            SetDefaultService(validationService);
        }

        #region IEntityValidationService<T> Members

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entityObject"></param>
        /// <param name="actionType"></param>
        /// <returns></returns>
        public ValidationResult Validate(T entityObject, ValidationActionType actionType)
        {
            Guard.ArgumentNotNull(entityObject, "entityObject");

            return Service.Validate(entityObject, actionType);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="validator"></param>
        public void SetSuccessor(IEntityValidationService<T> validator)
        {
            Guard.ArgumentNotNull(validator, "validator");

            Service.SetSuccessor(validator);
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="service"></param>
        protected virtual void SetDefaultService(IEntityValidationService<T> service)
        {
            Guard.ArgumentNotNull(service, "service");

            if (!DependencyServiceLocator.Current.IsDefaultServiceRegistered<IEntityValidationService<T>>())
            {
                DependencyServiceLocator.Current.SetDefaultService<IEntityValidationService<T>>(service);
            }
        }
    }
}
